package com.example.sqliteviewer;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements DatabaseAdapter.OnDatabaseClickListener {

    private static final int FILE_SELECT_CODE = 1002;
    private RecyclerView recyclerView;
    private DatabaseAdapter adapter;
    private List<File> databaseFiles;
    private TextView emptyView;
    private DatabaseHistoryManager historyManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        setTitle("SQLite数据库查看器");
        
        recyclerView = findViewById(R.id.recyclerView);
        emptyView = findViewById(R.id.emptyView);
        Button btnSelectDatabase = findViewById(R.id.btnSelectDatabase);
        Button btnCreateDatabase = findViewById(R.id.btnCreateDatabase);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        databaseFiles = new ArrayList<>();
        adapter = new DatabaseAdapter(this, databaseFiles, this);
        recyclerView.setAdapter(adapter);
        
        // 初始化历史记录管理器
        historyManager = new DatabaseHistoryManager(this);
        
        // 设置选择数据库按钮的点击事件
        btnSelectDatabase.setOnClickListener(v -> selectDatabaseFile());
        
        // 设置新建数据库按钮的点击事件
        btnCreateDatabase.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, CreateDatabaseActivity.class);
            startActivity(intent);
        });
        
        scanForDatabases();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }
    }
    
    private void selectDatabaseFile() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        
        // 设置MIME类型过滤器，只显示数据库文件
        String[] mimeTypes = {"application/x-sqlite3", "application/octet-stream", "application/vnd.sqlite3"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        
        try {
            startActivityForResult(Intent.createChooser(intent, "选择SQLite数据库文件"), FILE_SELECT_CODE);
        } catch (ActivityNotFoundException ex) {
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null) {
            Uri selectedFileUri = data.getData();
            if (selectedFileUri != null) {
                handleSelectedFile(selectedFileUri);
            }
        }
    }
    
    private void handleSelectedFile(Uri fileUri) {
        try {
            String fileName = FileUtils.getPath(this, fileUri);

            Toast.makeText(this, fileName, Toast.LENGTH_LONG).show();
            
            // 检查文件是否为SQLite数据库文件
            if (!fileName.endsWith(".db") && !fileName.endsWith(".sqlite") && !fileName.endsWith(".sqlite3")) {
                Toast.makeText(this, "请选择SQLite数据库文件(.db, .sqlite, .sqlite3)", Toast.LENGTH_LONG).show();
                return;
            }

            // 将数据库路径添加到历史记录
            historyManager.addToHistory(fileName);
            
            // 打开数据库查看器
            Intent intent = new Intent(this, DatabaseViewerActivity.class);
            intent.putExtra("DATABASE_PATH", fileName);
            startActivity(intent);
            
        } catch (Exception e) {
            Toast.makeText(this, "无法打开文件: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    private void scanForDatabases() {
        databaseFiles.clear();
        
        // 扫描应用内部数据库
        File internalDbDir = new File(getApplicationInfo().dataDir + "/databases");
        scanDirectory(internalDbDir);
        
        // 扫描临时目录中的数据库文件
        File tempDir = new File(getFilesDir(), "temp_databases");
        scanDirectory(tempDir);
        
        // 添加历史记录中的数据库文件
        addHistoryDatabases();
        
        // 更新UI
        adapter.notifyDataSetChanged();
        
        if (databaseFiles.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        }
    }
    
    private void scanDirectory(File directory) {
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return;
        }
        
        File[] files = directory.listFiles();
        if (files == null) {
            return;
        }
        
        for (File file : files) {
            if (file.isDirectory()) {
                scanDirectory(file);
            } else if (file.getName().endsWith(".db") || 
                       file.getName().endsWith(".sqlite") || 
                       file.getName().endsWith(".sqlite3")) {
                databaseFiles.add(file);
            }
        }
    }

    @Override
    public void onDatabaseClick(File databaseFile) {
        // 将数据库路径添加到历史记录
        historyManager.addToHistory(databaseFile.getAbsolutePath());
        
        Intent intent = new Intent(this, DatabaseViewerActivity.class);
        intent.putExtra("DATABASE_PATH", databaseFile.getAbsolutePath());
        startActivity(intent);
    }
    
    /**
     * 添加历史记录中的数据库文件到列表
     */
    private void addHistoryDatabases() {
        List<String> historyList = historyManager.getHistoryList();
        
        for (String path : historyList) {
            File file = new File(path);
            if (file.exists() && file.isFile() && !databaseFiles.contains(file)) {
                databaseFiles.add(file);
            }
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 0, "清空历史记录");
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            historyManager.clearHistory();
            scanForDatabases();
            Toast.makeText(this, "历史记录已清空", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 刷新数据库列表
        scanForDatabases();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        scanForDatabases();
    }
}